package com.heima.search.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.UserSearchDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.service.AssociateWordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 陈辉
 * @data 2024 17:09
 */
@Service
public class AssociateWordServiceImpl implements AssociateWordService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 联想词
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        if (userSearchDto == null || StringUtils.isEmpty(userSearchDto.getSearchWords()))
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);

        //对ap_associate_words表进行分页模糊查询
        List<ApAssociateWords> list = mongoTemplate.find(Query
                .query(Criteria.where("associateWords").regex(userSearchDto.getSearchWords(), "i"))
                .with(PageRequest.of(1, userSearchDto.getPageSize()))
                , ApAssociateWords.class);

        return ResponseResult.okResult(list);
    }
}
